// pages/mine/mine.js
var app = getApp()
const db = wx.cloud.database()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        openid: "",
        user: {},
        isComplete: false
    },
	beInvited(){
		wx.navigateTo({
			url: '/pages/beinvited/beinvited',
		})
	},
	myTeams(){
		wx.navigateTo({
			url: '/pages/myteam/myteam',
		})
	},
	myMatchs() {
		wx.navigateTo({
			url: '/pages/mymatch/mymatch',
		})
	},
	gotoStatement(){
		wx.navigateTo({
			url: '/pages/statement/statement',
		})
	},
	changeAvatar(e){
		// 让用户选择一张图片
		wx.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: chooseResult => {
				// 将图片上传至云存储空间
				wx.cloud.uploadFile({
					// 指定上传到的云路径
					cloudPath: 'usersAvatar/avatar@'+new Date().getTime()+'openid='+this.data.openid+'.png',
					// 指定要上传的文件的小程序临时文件路径
					filePath: chooseResult.tempFilePaths[0],
					// 成功回调
					success: res => {
						console.log('上传成功', res)
						db.collection("users").doc(this.data.user._id).update({
							data:{
								avatarUrl:res.fileID
							}
						})
						//删除旧头像
						wx.cloud.deleteFile({
							fileList: [this.data.user.avatarUrl]
						}).then(res => {
							// handle success
							console.log("success")
						}).catch(error => {
							// handle error
						}).finally(sss=>{
							let avatar = "user.avatarUrl"
							this.setData({
								[avatar]: res.fileID
							})
						})
					},
				})
			},
		})
	},
    edit: function(e) {
        if (!this.data.noLogin) {
            wx.navigateTo({
                url: '/pages/personDetail/personDetail?openid=' + this.data.openid,
            })
        }
    },
    getUserProfile(e) {
        wx.getUserProfile({
            desc: '用于完善资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log(res)
                if (!this.data.user) {
                    console.log("用户不存在")
                    let userInfo = res.userInfo
                    userInfo["isComplete"] = false
                    userInfo["cardcolor"] = "#8E90B3"
                    userInfo["score"] = 0
                    userInfo["scoreCount"] = 0
					userInfo["sex"] = null
					userInfo["school"] = null
					userInfo["profession"] = null
					userInfo["skill"] = null
                    db.collection("users").add({
                        data: userInfo
                    })
					this.setData({
						user: userInfo,
					})
                    console.log(res.userInfo.avatarUrl)
                } else {
                    console.log("用户存在")
					// console.log(app.globalData.openid)
					this.getUser(app.globalData.openid)
					// this.fun_isComplete(this.data.openid)
                }
				this.setData({
					noLogin: false
				})
                app.globalData.noLogin = false //全局登录状态设置
            }
        })
    },
    //判断是否已完善信息
    // fun_isComplete(openid) {
    //     db.collection("users").where({
    //         _openid: openid
    //     }).get().then(res => {
    //         // console.log(res)
    //         this.setData({
    //             isComplete: res.data[0].isComplete
    //         })
    //         console.log(this.data.isComplete)
    //     })
    // },
    //获取user函数
    getUser(openid) {
        // console.log("user")
        db.collection("users").where({
            _openid: openid
        }).get().then(res => {
            console.log(res.data)
            this.setData({
                user: res.data[0]
            })
        })

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {
        // 查看是否有此用户
        this.getUser(this.data.openid)
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        if (!app.globalData.noLogin) {
            this.getUser(app.globalData.openid)
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // 查看登录状态和准备openid
        this.setData({
            noLogin: app.globalData.noLogin,
            openid: app.globalData.openid
        })

    }
})